package com.atguigu.controller;

import com.atguigu.domain.UcenterMember;
import com.atguigu.exceptionhandler.GUliException;
import com.atguigu.service.UcenterMemberService;
import com.atguigu.utils.ConstantWxtiesUtil;
import com.atguigu.utils.HttpClientUtils;
import com.atguigu.utils.JwtUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    @GetMapping("login")
    public String getWxCode(){
        String baseUrl ="https://open.weixin.qq.com/connect/qrconnect?"+
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUrl = ConstantWxtiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        String url = String.format(
                baseUrl,
                ConstantWxtiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu"
        );

        return "redirect:"+url;
    }

    @GetMapping("callback")
    public String callback(String code,String state) {
        try {
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxtiesUtil.WX_OPEN_APP_ID,
                    ConstantWxtiesUtil.WX_OPEN_APP_SECRET,
                    code
            );


            String result = HttpClientUtils.get(accessTokenUrl);

            Gson gson = new Gson();
            HashMap accesToken = gson.fromJson(result, HashMap.class);
            String access_token = (String) accesToken.get("access_token");
            String openid = (String) accesToken.get("openid");



            UcenterMember member = ucenterMemberService.getOpenIdMember(openid);
            if(member==null){
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                String userInfoUrl = String.format(baseUserInfoUrl, accesToken, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                ucenterMemberService.save(member);
            }
            //通过路径传递 token值
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            return "redirect:http://localhost:3000?token="+token;
        } catch (Exception e) {
            throw new GUliException(20001,"登录失败");
        }


    }
}
